/**
 * @author marylin
 * time: 20120713
 * log:
 * 	1:增加vttkeymove对象来处理上下左右移动问题
 */

 
var _VttPos = {
   domChangeTime : 0,
   getPos : function(element, root_ele )
   {
       var x = 0;
       var y = 0;
       var ele = element;
       if ( ! root_ele ) root_ele = document.body;
       //找到父定位元素,并计算出在父定位元素中的位置.如果父定位没有,则默认为body
       while( ele && ele != root_ele )
       {
           x += ele.offsetLeft;
           y += ele.offsetTop;
           ele = ele.offsetParent;
       }
       return { x: x  , y: y , w: element.offsetWidth, h: element.offsetHeight };
   },
	
   findNearestDist : function( parentEle, children, offset, func )
   {
       var nearest = null;
       var dist = 10000000;
       for( var i = children.length - 1 ; i >= 0 ; i-- )
       {
           if ( children[i].offsetHeight <= 0 ) // style.display == "none" !
               continue;
               
           var xy = this.getPos( children[i], parentEle );
           var ndist = func( xy, offset );
           //比较所有父元素中距离最近的元素
           if ( ndist > 0 && ndist < dist )
           {
               dist = ndist;
               nearest = children[i];
           }
       }
       return [nearest, dist];
   },
   
   findNearest : function( element , func )
   {
       if ( ! element ) return null;
       var parentEle = element.offsetParent;
       if ( ! parentEle ) return null;
       var offset = this.getPos( element, parentEle );
       
       do {
           var near_a = this.findNearestDist( parentEle, parentEle.getElementsByTagName('a'), offset, func );
           var near_input = this.findNearestDist( parentEle, parentEle.getElementsByTagName('input'), offset, func );
           var near_select = this.findNearestDist( parentEle, parentEle.getElementsByTagName('select'), offset, func );
           var near_frame = this.findNearestDist( parentEle, parentEle.getElementsByTagName('iframe'), offset, func );

           var near1 = near_a[1] < near_input[1] ? near_a : near_input;
           var near2 = near1[1] < near_select[1] ? near1 : near_select;
           var near3 = near1[1] < near_frame[1] ? near2 : near_frame;
           
           if( near3[0] != null )
               return near3[0];
           parentEle = parentEle.offsetParent;
           offset = this.getPos( element, parentEle );
               
       }while( parentEle != null );
       
       return null;
   },
   
   left  : function( xy, offset )
   {
       var dx = xy.x - offset.x;
       if ( dx + xy.w/2 > 0 ) return -1;
       
       var dy = xy.y - offset.y;
       return  dx * dx  + dy * dy * 5;
   },
   
   right : function( xy, offset )
   {
       var dx = xy.x - offset.x;
       if ( dx <= offset.w/2 ) return -1;
       
       var dy = xy.y - offset.y;
       return dx * dx  + dy * dy * 5;
   },
   
   up : function( xy, offset )
   {
       var dy = xy.y - offset.y;       
       //与当前元素同高度或比当前高度还要高.以致上面没有元素移动返回-1
       if ( dy + xy.h /2> 0 ) return -1;
       
       dx = xy.x - offset.x;
       return dx * dx * 5  + dy * dy;
   },
   
   down : function( xy, offset )
   {
       var dy = xy.y - offset.y;
       if ( dy <= offset.h/2 ) return -1;
       
       dx = xy.x - offset.x;
       return dx * dx * 5  + dy * dy;
   },
   
   getNext : function( element, nextidname )
   {
       var nextid = element.getAttribute( nextidname );
       if ( nextid  )
       {
           var m_currentEle = document.getElementById( nextid );
           if ( m_currentEle.offsetWidth != 0 )
              return m_currentEle;
       }
       return null;
   },
   
   findNextEle : function( element, direction )
   {
       var nb_attr =  direction + "id";
       var nb_name =  direction + "_element";
       var tm_name = direction + "_findtime";
       
       if ( !! element[ nb_name ] )
       {
           if ( element[ nb_name ].style.offsetWidth == 0 )
           {
               this.domChangeTime ++;
               element[ nb_name ] = null;
               element.xy = null;
           }
           else if (  (! element[ tm_name ] ) || ( element[tm_name] < this.domChangeTime ) )
           {
               element[ nb_name ] = null;
               element.xy = null;
           }
       }

       if ( ! element[ nb_name ] )
       {
           element[ nb_name ] = this.getNext( element, nb_attr );
           element[ tm_name ] = this.domChangeTime;
       }
       
       if ( ! element[ nb_name ] )
       {
           element[ nb_name ] = this.findNearest( element, this[direction] );
           element[ tm_name ] = this.domChangeTime;
       }
       
       return element[ nb_name ];  
   },
   
   findLeft : function( element )
   {
       return this.findNextEle( element, "left")?this.findNextEle( element, "left"):element;
   },
   
   findRight : function( element )
   {
       return this.findNextEle( element, "right")?this.findNextEle( element, "right"):element;
   },
   findUp : function( element )
   {
       return this.findNextEle( element, "up")?this.findNextEle( element, "up"):element;
   },
   findDown : function( element )
   {
       return this.findNextEle( element, "down")?this.findNextEle( element, "down"):element;
   },
};
function VatataKeyMoveClass(){
	var m_prevEle = null;
	var m_currentEle = null;
	var m_eventTransitionObj = null;
	
    var m_focusClass = "currentFocus";
    var m_blurClass = "currentFocus";
    //设置高亮和blur的函数,需要变更高亮的时候调用一下
    this.setBlurAndFocusClass = function(blurClass,focusClass){
    	m_focusClass = focusClass;
    	m_blurClass = blurClass;
    }
    //失去焦点时调用(每次高亮之前调用,取消上一次高亮的ClassName)
    function doBlur(ele){   	
    	if(!ele||!ele.className)
    		return;
    	
		m_prevEle = ele;
    	var reg = new RegExp(m_blurClass,"g");
    	var _classname = ele.className.replace(reg,"");
    	ele.className = _classname;
    }
//    var focus_timer = null;
    //获得焦点时调用
    function doFocus(ele){
    	if(!ele)
    		return;
    		
    	m_currentEle = ele;
		ele.className+=(" "+m_focusClass);
		ele.focus();
    }
    function doEnter(ele){
    	if(document.all)
			ele.click();
		else{
			var ev=document.createEvent("HTMLEvents");
			ev.initEvent("click",false,true);
			ele.dispatchEvent(ev);
		}
    }
    //提供全局blur和focus高亮接口,供用户自定义操作
    //可能暂时永不到,不过先提供出功能.为下面的up down left right调整做准备.
    this.doBlur = function(){var _ele = m_currentEle;if(arguments.length>=1)_ele=arguments[1];doBlur(_ele);}
    this.doFocus = function(){var _ele = m_currentEle;if(arguments.length>=1)_ele=arguments[1];doFocus(_ele);}
    this.doEnter = function(){var _ele = m_currentEle;if(arguments.length>=1)_ele=arguments[1];doEnter(_ele)}
    //为外面提供移动调用接口
    this.up = function(){doBlur(m_currentEle);m_currentEle= _VttPos.findUp( m_currentEle );doFocus(m_currentEle);}
    this.down = function(){doBlur(m_currentEle);m_currentEle = _VttPos.findDown( m_currentEle );doFocus(m_currentEle);}
    this.left = function(){doBlur(m_currentEle);m_currentEle = _VttPos.findLeft( m_currentEle );doFocus(m_currentEle);}
    this.right = function(){doBlur(m_currentEle);m_currentEle = _VttPos.findRight( m_currentEle );doFocus(m_currentEle);}
    
    const KEY_W = 87
    const KEY_S = 83;
    const KEY_A = 65;
    const KEY_D = 68;
    const KEY_SPACE=32;
    const KEY_F = 70;
    
//    const KEY_UP = 19;
//    const KEY_LEFT = 21;
//    const KEY_RIGHT = 22;
//    const KEY_DOWN = 20;
//    const KEY_ENTER = 66;
    this.vttkeymove = function(e){
    	if(m_currentEle)
    		doBlur(m_currentEle);
    	
		switch(e.keyCode){
			case KEY_W:{m_currentEle = _VttPos.findUp( m_currentEle );}break;
			case KEY_A:{m_currentEle = _VttPos.findLeft( m_currentEle );}break;
			case KEY_S:{m_currentEle = _VttPos.findDown( m_currentEle);}break;
			case KEY_D:{m_currentEle = _VttPos.findRight( m_currentEle );}break;
			case KEY_F:{
				doEnter(m_currentEle);
			}break;
		}
		if(m_currentEle)
			doFocus(m_currentEle)
    }
	this.getPrevEle = function(){
		return m_prevEle;
	}
    this.getCurrentEle = function(){
    	return m_currentEle;
    }
    this.openDefaultVttKey = function(){
    	//打开默认键值转换
    	m_eventTransitionObj.openDefaultTransition();
    }
	this.addVttKey = function(oldkey,newkey){
		//添加键值转换
		m_eventTransitionObj.addKeysTransition(oldkey,newkey);
	}
	this.addVttKeys = function(oldkeys,newkeys){
		//添加一组键值转换
		m_eventTransitionObj,addKeysTransition(oldkeys,newkeys);
	}
	this.clearVttKey = function(key){
		//移除该键值转换
		m_eventTransitionObj.removeKeyTransition(key);
	}
	this.clearAllVttKey = function(){
		//清除所有键值转换
		m_eventTransitionObj.clear();
	}
	this.initVttKeymove = function(id){
		initWae();
		
//        //获取body中第一个input或者a,来从第一个移动的元素开始找
//        var _body_first_ele = document.body.innerHTML.match(/<(a|input+)/)[1];
//        var eles = document.getElementsByTagName(_body_first_ele);
//        //focus前如果不给定blurClass和focusClass则用默认的currentFocus做高亮class
//        //如果需要设置则
//        this.setBlurAndFocusClass(blurclass,focusclass);
		
		//先清除原来的高亮元素,再设置focus元素
        if(m_currentEle)
        	doBlur(m_currentEle)
		doFocus(id);
	}
	function initWae(){
		//用公共对象创建WAE对象如果失败再本地创建避免耦合
		if(window.VatataPublic&&window.VatataPublic!=null){
			m_eventTransitionObj = VatataPublic.createAndroidPlug("EventTransition");
		}
		if(!m_eventTransitionObj){
			if (wae.can("EventTransition") == false) {
	            return;
	        }
	        m_eventTransitionObj = wae.create("EventTransition");
	        if (m_eventTransitionObj == null) {
	            return;
	        }
		}
	}
	//默认初始化 body 下第一个
	this.initDefaultVttKeymove = function(){
    	initWae();
    	this.openDefaultVttKey();
    	
        document.addEventListener("keydown",this.vttkeymove,false);
        
        var _ele = document;
        var _ele_body = _ele.body;
        
        if(arguments.length>=1&&arguments[0]){
        	_ele = arguments[0];
        	_ele_body = _ele;
        }
        
        //获取body中第一个input或者a,来从第一个移动的元素开始找
        var _body_first_ele = _ele_body.innerHTML.match(/<(input|a|select|iframe+)/)[1];
        
        var eles = _ele.getElementsByTagName(_body_first_ele);
        //先清除原来的高亮元素,再设置focus元素
        if(m_currentEle)
        	doBlur(m_currentEle)
        	
		doFocus(eles[0])
    }
    this.initVttKeymoveById = function(id){
		initWae();
    	this.openDefaultVttKey();
    	
        document.addEventListener("keydown",this.vttkeymove,false);
        //先清除原来的高亮元素,再设置focus元素
        if(m_currentEle)
        	doBlur(m_currentEle)
        	
        doFocus(id)
    }
}
var VatataKeyMove = new VatataKeyMoveClass();
